package com.triptogether.shoppinglist.fragments;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.triptogether.R;
import com.triptogether.baseclasses.BaseFragment;
import com.triptogether.shoppinglist.adapters.ProductsListAdapter;
import com.triptogether.utils.db.DBManager;
import com.triptogether.utils.db.models.Product;
import com.triptogether.utils.db.models.ShoppingList;

public class ProductsListFragment extends BaseFragment {

	public static final String ARG_SHOPPING_LIST_ID = "ARG_SHOPPING_LIST_ID";
	
	ProductsListAdapter productsListAdapter;
	ShoppingList productsShoppingList;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_products_list, container, false);
	}
	
	public void onStart() {
		super.onStart();
		
		// Get the id of the shoppingList we got from the fragments arguments
		long shoppingListId = getArguments().getLong(ARG_SHOPPING_LIST_ID);
		
		// Find the ShoppingList by the id, and save this ShoppingList for future use
		productsShoppingList = DBManager.getInstance(getActivity()).findShoppingListById(shoppingListId);
		
		// Initialize the listView and its adapter
		ListView lv = (ListView) getView().findViewById(R.id.listview_products);
		productsListAdapter = new ProductsListAdapter(getActivity(), shoppingListId);
		lv.setAdapter(productsListAdapter);
	};

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
	    super.onCreateOptionsMenu(menu, inflater);
		inflater.inflate(R.menu.products_list_fragment_menu, menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case R.id.menu_item_add_product:
				// Create the product in DB
				Product createProduct = DBManager.getInstance(getActivity()).createProduct(
				        getString(R.string.new_product_default_name),
				        productsShoppingList);

				// Add this products to the listView
				productsListAdapter.add(createProduct);
				return true;
		}
		return super.onOptionsItemSelected(item);
	}
}
